import json

import requests
from django.http import JsonResponse
from course import get_course, models


# Create your views here.
def login(request):
    data = json.loads(request.body.decode())
    num = data.get('num', None)
    pwd = data.get('pwd', None)
    if request.method == "POST" and num and pwd:
        success, s = get_course.login(num, pwd)
        if success:
            user = models.User.objects.filter(number=num)
            if user:
                user[0].cookie = ';'.join([f'{c.name}={c.value}' for c in s.cookies])
                user[0].save()
            else:
                info, week = get_course.get_user_info_and_week(s)
                models.User(number=num, password=pwd, name=info['name'], college=info['college'], major=info['major'], _class=info['class'], cookie=';'.join([f'{c.name}={c.value}' for c in s.cookies])).save()
            request.session['num'] = num
            return JsonResponse({'status': 0, 'msg': '', 'data': {}})
        else:
            return JsonResponse({'status': 1, 'msg': '用户名或密码错误', 'data': {}})
    return JsonResponse({'status': 1, 'msg': '', 'data': {}})


def user_info(request):
    num = request.session.get('num', None)
    if num:
        user = models.User.objects.filter(number=num)
        if user:
            info = {'name': user[0].name, 'num': user[0].number, 'college': user[0].college, 'major': user[0].major, 'class': user[0]._class}
            return JsonResponse({'status': 0, 'msg': '', 'data': info})
    return JsonResponse({'status': -1, 'msg': '', 'data': {}})


def get_user_exam(request):
    num = request.session.get('num', None)
    if num:
        user = models.User.objects.filter(number=num)
        if user:
            return course(user[0], 'exam')
    return JsonResponse({'status': -1, 'msg': '', 'data': {}})


def get_user_score(request):
    num = request.session.get('num', None)
    if num:
        user = models.User.objects.filter(number=num)
        if user:
            return course(user[0], 'score')
    return JsonResponse({'status': -1, 'msg': '', 'data': {}})


def get_user_course(request):
    num = request.session.get('num', None)
    if num:
        user = models.User.objects.filter(number=num)
        if user:
            return course(user[0], 'course')
    return JsonResponse({'status': -1, 'msg': '', 'data': {}})


def course(user, kind):
    s = requests.session()
    s.headers.update({
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'User-Agent': 'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/80.0.3987.132Safari/537.36',
        'Cookie': user.cookie
    })
    f = None
    if kind == 'course':
        f = get_course.get_course
    elif kind == 'score':
        f = get_course.get_scores
    elif kind == 'exam':
        f = get_course.get_exams
    elif kind == 'info':
        f = get_course.get_user_info_and_week
    if f:
        try:
            return JsonResponse({'status': 0, 'msg': '', 'data': {kind: f(s), 'time': get_course.get_time(),
                                                                  'week': get_course.get_user_info_and_week(s)[1]}})
        except Exception as e:
            success, s = get_course.login(user.number, user.password)
            if success:
                user.cookie = ';'.join([f'{c.name}={c.value}' for c in s.cookies])
                user.save()
                return JsonResponse({'status': 0, 'msg': '', 'data': {kind: f(s), 'time': get_course.get_time(), 'week': get_course.get_user_info_and_week(s)[1]}})
            else:
                return JsonResponse({'status': -1, 'msg': '', 'data': {}})
    return JsonResponse({'status': -1, 'msg': '', 'data': {}})
